package com.example.framework.security.core.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.example.framework.security.config.SecurityProperties;
import com.example.framework.security.core.util.SecurityFrameworkUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Collection;
import java.util.HashSet;

@RequiredArgsConstructor
public class FeignInterceptor implements RequestInterceptor {

    private final SecurityProperties securityProperties;

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            // 目前只传递 jwtToken
            String jwtToken = SecurityFrameworkUtils.obtainAuthorization(request, securityProperties.getHeaderName());
            if (ObjectUtil.isNotEmpty(jwtToken)) {
                // 添加请求头
                template.header(securityProperties.getHeaderName(), jwtToken);
                // 添加 cookie
                Collection<String> cookies = template.headers().computeIfAbsent(HttpHeaders.COOKIE, v -> new HashSet<>());
                cookies.add(jwtToken);
            }
        }
    }

}
